package com.superbytecode.cloud.safety.ratelimit;

import com.superbytecode.cloud.safety.ratelimit.exception.RateLimitException;
import com.superbytecode.cloud.safety.ratelimit.model.RateLimitReq;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.util.Objects;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: beacon-cloud
 * @Package: com.superbytecode.cloud.safety.ratelimit
 * @ClassName: RateLimitAspect
 * @Description: [接口限流AOP]
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/11/13 16:23
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Slf4j
@Aspect
public class RateLimitAspect {
    @Around("@annotation(rateLimitAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimitAnnotation) throws Throwable {
        Object[] args = joinPoint.getArgs();
        RateLimitType rateLimitType = rateLimitAnnotation.type();
        RateLimiter rateLimiter = RateLimitFactory.bind(rateLimitType);
        if (Objects.isNull(rateLimiter)) {
            throw new RateLimitException("未找到限流器:" + rateLimitType);
        }
        RateLimitReq rateLimitReq = new RateLimitReq()//
                .setJoinPoint(joinPoint)//
                .setSpEl(rateLimitAnnotation.spEl())//
                .setRules(rateLimitAnnotation.rules());
        if (!rateLimiter.passed(rateLimitReq)) {
            throw new RateLimitException(rateLimitAnnotation.handle());
        }
        return joinPoint.proceed(args);
    }
}